//
//  GRXOAuthController.m
//  1-MushroomStreet-自定义tabbar
//
//  Created by xmg on 16/1/12.
//  Copyright © 2016年 grx. All rights reserved.
//

#import "GRXOAuthController.h"
#import <AFHTTPSessionManager.h>
#import "UserAccount.h"
@interface GRXOAuthController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation GRXOAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加载新浪登录网页
    [self loadPage];
    
    //设置导航条
    [self setUpNavigationg];
}


#pragma mark ---新浪登录加载
- (void)loadPage{
    NSString *urlStr = [NSString stringWithFormat:@""@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",app_key,redirect_uri];
    //根据字符串创建url
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //创建reqest对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //设置代理
    self.webView.delegate = self;
    
    [self.webView loadRequest:request];
}

#pragma mark ---webView代理方法

//每次请求都会回调这个方法,如果返回NO,代表不允许发送新的请求,如果返回YES,代表允许发送新的请求
/*
 参数含义
 1. 谁要发送请求
 2. 当前要请求什么请求(可以获取要加载网页的地址)
 */

/*
 请求网页类型
 登录网页:https://api.weibo.com/oauth2/authorize?client_id=382545027&redirect_uri=http://www.mogujie.com
 请求授权:https://api.weibo.com/oauth2/authorize
 
 授权成功:http://www.mogujie.com/?code=5c48fbe5cff60d721877f461989c8588
 
 取消授权:http://www.mogujie.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
 */

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *urlStr = request.URL.absoluteString;
    
    if (urlStr == nil) {
        return NO;
    }
    
    //1.判断是否是以http://www.mogujie.com开头的url,以过滤掉非授权页
    if ([urlStr hasPrefix:redirect_uri] == NO) {
        return YES;
    }
    
    //2.处理回调地址
    NSString *code = @"code=";
    NSString *queryStr = request.URL.query;
    
    //如果能够进来,就说明用户已经授权,那么就不在申请新的请求
    if ([queryStr hasPrefix:code]) {
//        NSLog(@"已经授权");
        
        //2.1 截取出成功页的code=后面的字符串
        NSString *codeStr = [queryStr substringFromIndex:code.length];
        
        //2.2 利用已经授权的RequestToken换取AccessToken
        [self loadAccessToken:codeStr];

        return NO;
    }
    
    
    //用户取消授权,关闭webView窗口,不再发送请求
//    NSLog(@"取消授权");
    [self close];
    return NO;

}

//开始加载网页的时候调用
- (void)webViewDidStartLoad:(UIWebView *)webView{
//    NSLog(@"开始加载");
}

//结束加载网页时调用
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    NSLog(@"加载完成");
}

//加载网页发生错误时调用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
//    NSLog(@"加载错误");
}

#pragma mark ---根据已经授权的RequestToken换取AccessToken
- (void)loadAccessToken:(NSString *)codeStr{
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://api.weibo.com/"]];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain",nil];
    NSString *path = @"oauth2/access_token";
    NSDictionary *parameter = @{
        @"client_id": app_key,
        @"client_secret": app_secret,
        @"grant_type": @"authorization_code",
        @"code": codeStr,
        @"redirect_uri": redirect_uri
    };
    [manager POST:path parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //服务器返回一个json数据
        //包含申请到的access_token(令牌)
       
        //安全校验
        if (responseObject == nil) {
            //没有数据
            return ;
        }
        
        //字典转模型
        UserAccount *account = [UserAccount grx_userAccountWithDict:responseObject];
        
        NSLog(@"%@",account);
        [account saveUserAccount];
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:GRXChangeRootViewControllerNotification object:nil userInfo:@{@"message": @YES}];
        
        
        NSLog(@" [account saveUserAccount] = %zd",[account saveUserAccount]);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
   
}



#pragma mark ---导航栏设置
- (void)setUpNavigationg{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStyleDone target:self action:@selector(close)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"填充" style:UIBarButtonItemStyleDone target:self action:@selector(full)];
}

#pragma mark ---事件监听
- (void)close{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)full{
    //OC和JS交互
    NSString *jsCode = @"document.getElementById('userId').value='467735740@qq.com';document.getElementById('passwd').value='5578777132';";
    
    //执行js代码
    [self.webView stringByEvaluatingJavaScriptFromString:jsCode];
    
}

@end
